package github.fafaovo.common.commands;

import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import github.fafaovo.common.mycapability.ISpeedUpCapability;
import github.fafaovo.core.registry.CommonSetupEventHandler;
import github.fafaovo.deepcapacity;
import github.fafaovo.network.NetworkRegistryHandler;
import github.fafaovo.network.Packet.Power;
import net.minecraft.command.CommandSource;
import net.minecraft.command.Commands;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.fml.network.PacketDistributor;
import net.minecraftforge.server.permission.PermissionAPI;
import net.minecraftforge.server.permission.context.PlayerContext;


public class SetPowerCommand {
    // [then是空格] 即命令是/example getHand
    public SetPowerCommand(CommandDispatcher<CommandSource> dispatcher)
    {
        dispatcher.register(Commands.literal(deepcapacity.MOD_ID)
                .then(Commands.literal("setpower")
                .then(Commands.argument("count", IntegerArgumentType.integer(0))
                        .executes(
                (c)->{
                    return setPower(c.getSource(),IntegerArgumentType.getInteger(c, "count"));
                }
        ))));
    }
    private int setPower(CommandSource source,int count) throws CommandSyntaxException
    {
        ServerPlayerEntity player = source.asPlayer();
        //有管理员权限才能运行的指令
        String permissionKey = "a.random.permission.key";
        if (PermissionAPI.hasPermission(player.getGameProfile(), permissionKey, new PlayerContext(player))) {
            // 在有权限的时候执行操作
            LazyOptional<ISpeedUpCapability> capability = player.getCapability(CommonSetupEventHandler.SPEED_UP_CAPABILITY);
            capability.ifPresent((b)->{
                b.setLevel(count);
                NetworkRegistryHandler.CHANNEL.send(
                        PacketDistributor.PLAYER.with(
                                ()->(ServerPlayerEntity) player),//为了区分不同的玩家
                        new Power(b.getLevel())
                );
            });
            return 1;
        }
        return 1;


    }
}
